package cn.bopomo.dealer.base.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.bopomo.dealer.base.db.IAuGroupDAO;
import cn.bopomo.dealer.base.db.IAuthorizeDAO;
import cn.bopomo.dealer.base.db.IModuleDAO;
import cn.bopomo.dealer.base.db.IOperatorDAO;
import cn.bopomo.dealer.base.exception.SystemException;
import cn.bopomo.dealer.base.service.IOperatorService;
import cn.bopomo.dealer.base.util.Page;
import cn.bopomo.dealer.base.util.ResultCode;
import cn.bopomo.dealer.base.util.SecurityUtil;
import cn.bopomo.dealer.base.vo.AuGroup;
import cn.bopomo.dealer.base.vo.AuthorizeList;
import cn.bopomo.dealer.base.vo.ModuleList;
import cn.bopomo.dealer.base.vo.OperatorDetail;

public class OperatorServiceImpl implements IOperatorService {

	private IOperatorDAO operatorDAO;
	private IAuthorizeDAO authorizeDAO;
	private IModuleDAO moduleDAO;
	private IAuGroupDAO groupDAO;
	private Log log = LogFactory.getLog(getClass());
	
	public void setGroupDAO(IAuGroupDAO groupDAO) {
		this.groupDAO = groupDAO;
	}

	public void setAuthorizeDAO(IAuthorizeDAO authorizeDAO) {
		this.authorizeDAO = authorizeDAO;
	}

	public void setModuleDAO(IModuleDAO moduleDAO) {
		this.moduleDAO = moduleDAO;
	}

	public String checkLoginName(String loginName) {
		return this.operatorDAO.selectOperator(loginName);
	}

	public OperatorDetail login(String loginName, String pwd) {
		// TODO Auto-generated method stub
		pwd = SecurityUtil.MD5(pwd);
		return this.operatorDAO.selectOperator(loginName,pwd);
	}

	public String addOperator(OperatorDetail od) {
		
		String checkReturn = this.checkLoginName(od.getLoginName());
		
		if (ResultCode.OP_SUCCESS.equals(checkReturn)){
			return this.operatorDAO.insertOperator(od);
		}else{
			return checkReturn;
		}

		
	}

	public String modifyOperator(OperatorDetail od) {
	
		return this.operatorDAO.updateOperator(od);
	}

	public String deleteOperatorThorough(OperatorDetail od) throws SystemException {
		List op_list = this.operatorDAO.selectOperatorsByParent(od);
		if (op_list != null && op_list.size()>0)
			return ResultCode.OP_HAS_CHILD;
		
		return this.operatorDAO.deleteOperator(od);
	}

	public List getChildOperator(OperatorDetail parent,List content) {
		
		List tmp = null;
		try {//根据父类查找子类列表
			tmp = this.operatorDAO.selectOperatorsByParent(parent);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return content;
		}
		if (tmp != null && tmp.size()>0){//当子类列表不为空时，进行迭代操作
			for (Iterator it = tmp.iterator();it.hasNext();){
				OperatorDetail tmpOd = (OperatorDetail)it.next();
				//如果该子类仍然有下属的子类，进行迭代
				if (tmpOd.getHasChild().equals("1")){
					List newList = new ArrayList();
					this.getChildOperator(tmpOd,newList);
					content.add(newList);
				}else{
					content.add(tmpOd);
				}
			}
		}
		return content;
	}

	public void setOperatorDAO(IOperatorDAO operatorDAO) {
		this.operatorDAO = operatorDAO;
	}

	public String getAuthorizeAction(String tag) throws SystemException {
		
		AuthorizeList authorize = this.authorizeDAO.selectAuthorize(tag);
		
		if (authorize != null)
			return authorize.getAuthorizeAction();
		return null;
	}

	
	
	public List getAuthorizeListByTag(String authorizeList) throws SystemException{
		List listAuthorize = new ArrayList();
		String[] authorizes = authorizeList.split("/");
		for (int i=0;i<authorizes.length;i++){
			AuthorizeList tmp = this.authorizeDAO.selectAuthorize(authorizes[i]);
			if (tmp != null)
				listAuthorize.add(tmp);
		}
		
		if (listAuthorize.size()<=0)
			return null;
		
		return listAuthorize;
	}
	
	public List getAuthorizeList() throws SystemException{
		return this.authorizeDAO.selectAuthorize();
	}
	
	protected AuthorizeList getAuthorize(AuthorizeList authorize) throws SystemException{
		return this.authorizeDAO.selectAuthorizeByName(authorize.getAuthorizeName(),authorize.getModuleList().getMid().intValue());
	}
	
	protected AuthorizeList getAuthorizeByTag(String authorize_tag) throws SystemException{
		return this.authorizeDAO.selectAuthorize(authorize_tag);
	}
	
	public List getAuthorizesByGroup(Integer gid) throws SystemException{
		AuGroup group = this.getGroup(gid);
		String tagList = this.generatePhaseOfInCondition(group.getGroupAuthorize(),"/");
		return this.authorizeDAO.selectAuthorizeByTags(tagList);
	}
	
	public List getAuthorizesByModule(Integer mid) throws SystemException{
		ModuleList module = this.getModule(mid);
		
		return this.authorizeDAO.selectAuthorize(module);
	}
	
	public String checkAuthorizeValidate(AuthorizeList authorize){
		String result = ResultCode.OP_FAILED;
		
		if (authorize == null)
			return result;
		
		try {
			if (authorize.getAuthorizeAction().equals("")){
				return ResultCode.OP_AUTH_ACTION_NULL;
			}else if (authorize.getAuthorizeName().equals("") || this.getAuthorize(authorize) != null){
				return ResultCode.OP_THE_NAME_EXISTS;
			}else if (authorize.getAuthorizeTag().equals("") || this.getAuthorizeByTag(authorize.getAuthorizeTag())!= null){
				return ResultCode.OP_THE_TAG_EXISTS;
			}else{
				return ResultCode.OP_SUCCESS;
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
		}
		
		
		return result;
		
	}
	
	
	public String modifyAuthorize(AuthorizeList authorize) throws SystemException{
		
//		String aaa = this.checkAuthorizeValidate(authorize);
//		if(!aaa.equals(ResultCode.OP_SUCCESS)){
//			return aaa;
//		}
//		AuthorizeList tmpAuthorize = this.authorizeDAO.selectAuthorize(authorize.getAid());
//		if (tmpAuthorize == null){
//			return ResultCode.OP_FAILED;
//		}
//		AuthorizeList tmpAuthorize = this.authorizeDAO.selectAuthorize(authorize.getAuthorizeTag());
////		if (tmpAuthorize != null && authorize.getAid().intValue()!= tmpAuthorize.getAid().intValue())
//			return ResultCode.OP_THE_TAG_EXISTS;
//		
//		tmpAuthorize = this.authorizeDAO.selectAuthorizeByName(authorize.getAuthorizeName(),authorize.getModuleList().getMid().intValue());
//		
//		if (tmpAuthorize != null && authorize.getAid().intValue()!= tmpAuthorize.getAid().intValue())
//			return ResultCode.OP_THE_NAME_EXISTS;
		
		
		AuthorizeList tmpAuthorize = this.authorizeDAO.selectAuthorizeByNameOrTagNotId(
																	authorize.getAuthorizeName(), 
																	authorize.getAuthorizeTag(), 
																	authorize.getAid());
		if (tmpAuthorize == null){
			tmpAuthorize = this.authorizeDAO.selectAuthorize(authorize.getAid());
		}else{
			//这里不能分开是name还是tag重复??????????????????????????????????????????????
			return ResultCode.OP_THE_NAME_EXISTS;
		}
		
		
		
		//判断传入参数没有重要性修改
		if (authorize.getAuthorizeName().equalsIgnoreCase(tmpAuthorize.getAuthorizeName()) && tmpAuthorize.getAuthorizeTag().equals(authorize.getAuthorizeTag())){
			
			authorize.setModifyDate(new Date());
			return this.authorizeDAO.updateAuthorize(authorize);
			
		}else if (!authorize.getAuthorizeName().equalsIgnoreCase(tmpAuthorize.getAuthorizeName()) && tmpAuthorize.getAuthorizeTag().equals(authorize.getAuthorizeTag())){//判断是否只修改了权限的名称
			tmpAuthorize.setAuthorizeName(authorize.getAuthorizeName());
			tmpAuthorize.setModifyDate(new Date());
			return this.authorizeDAO.updateAuthorize(tmpAuthorize);
			
		}else {
			//当发生权限标识改变的时候，修改原有权限组本身拥有该权限的标识替代为最新的标识
			String result = ResultCode.OP_FAILED;
			tmpAuthorize.setModifyDate(new Date());
			
			List group_list = this.groupDAO.selectGroupsByAuthorize(tmpAuthorize.getAuthorizeTag());
			
			if (group_list != null){
				for (Iterator it = group_list.iterator();it.hasNext();){
					AuGroup ag = (AuGroup)it.next();
					ag.setGroupAuthorize(ag.getGroupAuthorize().replaceAll(tmpAuthorize.getAuthorizeTag(),authorize.getAuthorizeTag()));
					result = this.groupDAO.updateAuGroup(ag);
				}
			}
			
			tmpAuthorize.setAuthorizeTag(authorize.getAuthorizeTag());

			result = this.authorizeDAO.updateAuthorize(tmpAuthorize);
			
			return result;
		}
		
	}
	
	public String deleteAuthorize(AuthorizeList authorize) throws SystemException{
		String result = ResultCode.OP_FAILED;
		List group_list = this.groupDAO.selectGroupsByAuthorize(authorize.getAuthorizeTag());
		if (group_list != null){
			for (Iterator it = group_list.iterator();it.hasNext();){
				AuGroup ag = (AuGroup)it.next();
				StringBuffer sauthorize = new StringBuffer(ag.getGroupAuthorize());
				int index = sauthorize.indexOf(authorize.getAuthorizeTag());
				sauthorize.delete(index,index + authorize.getAuthorizeTag().length() + 1);
				
				ag.setGroupAuthorize(sauthorize.toString());
				result = this.groupDAO.updateAuGroup(ag);
			}
			result = this.authorizeDAO.deleteAuthorize(authorize);
		}
		return result;
	}
	
	public String getModuleAction(String tag) throws SystemException {
		
		ModuleList module = this.moduleDAO.selectModule(tag);
		
		if (module != null)
			return module.getModuleAction();
		return null;
	}
	
	public String modifyModule(ModuleList module) throws SystemException{
		ModuleList tmpModule = this.moduleDAO.selectModule(module.getModuleTag());
		if (tmpModule != null && module.getMid().intValue()!= tmpModule.getMid().intValue())
			return ResultCode.OP_THE_TAG_EXISTS;
		
		tmpModule = this.moduleDAO.selectModuleByName(module.getModuleName());
		
		if (tmpModule != null && module.getMid().intValue()!= tmpModule.getMid().intValue())
			return ResultCode.OP_THE_NAME_EXISTS;
		
		//判断传入参数没有重要性修改
		if (module.getModuleName().equalsIgnoreCase(tmpModule.getModuleName()) && tmpModule.getModuleTag().equals(module.getModuleTag())){
			
			module.setModifyDate(new Date());
			return this.moduleDAO.updateModule(module);
			
		}else if (!module.getModuleName().equalsIgnoreCase(tmpModule.getModuleName()) && tmpModule.getModuleTag().equals(module.getModuleTag())){//判断是否只修改了权限的名称
			
			module.setModifyDate(new Date());
			return this.moduleDAO.updateModule(module);
			
		}else {
			//当发生权限标识改变的时候，修改原有权限组本身拥有该权限的标识替代为最新的标识
			//String result = ResultCode.OP_FAILED;
			module.setModifyDate(new Date());
			/*
			List op_list = this.operatorDAO.selectOperatorsByModule(tmpModule.getModuleTag());
			
			if (op_list != null){
				for (Iterator it = op_list.iterator();it.hasNext();){
					OperatorDetail od = (OperatorDetail)it.next();
					od.setModuleAuthorize(od.getModuleAuthorize().replaceAll(tmpModule.getModuleTag(),module.getModuleTag()));
					result = this.operatorDAO.updateOperator(od);
				}
				result = this.moduleDAO.updateModule(module);
			}
			*/
			
			//return result;
			return this.moduleDAO.updateModule(module);
		}
	}
	
	public String deleteModule(ModuleList module) throws SystemException{
		
		String result = ResultCode.OP_FAILED;
		List op_list = this.operatorDAO.selectOperatorsByModule(module.getModuleTag());
		
		if (op_list != null){
			for (Iterator it = op_list.iterator();it.hasNext();){
				OperatorDetail od = (OperatorDetail)it.next();
				
				StringBuffer smodule = new StringBuffer(od.getModuleAuthorize());
				int index = smodule.indexOf(module.getModuleTag());
				smodule.delete(index,index + module.getModuleTag().length() + 1);
				od.setModuleAuthorize(smodule.toString());
				
				result = this.operatorDAO.updateOperator(od);
			}
			result = this.moduleDAO.deleteModule(module);
		}
		
		return result;
		
	}

	public Map getModuleListByTag(String groups) throws SystemException{
		Map lstModule = new HashMap();
		
		String[] groupArray = groups.split("/");
		if (groupArray.length == 1 && groups.equals("000")){
			List groupList = this.getGroupList();
			for (int i = 0;i < groupList.size();i++){
				AuGroup tmp_group = (AuGroup)groupList.get(i);
				if (tmp_group != null){
					lstModule.put(tmp_group.getModuleList().getModuleTag(),tmp_group.getModuleList());
				}
			}
		}else{
			for (int i=0;i<groupArray.length;i++){
				AuGroup tmp_group = (AuGroup)this.groupDAO.selectGroup(new Integer(groupArray[i]));
				if (tmp_group != null){
					lstModule.put(tmp_group.getModuleList().getModuleTag(),tmp_group.getModuleList());
				}
			}
		}
		if (lstModule.size()<=0)
			return null;
		
		return lstModule;
	}
	
	public List getModuleList() throws SystemException{
		return this.moduleDAO.selectModules();
	}
	
	public Map getAuthorize(String group) throws SystemException{
		String[] groupArray = group.split("/");
		Map result = new HashMap();
		if (groupArray.length == 1 && group.equals("000")){
			List tmp_authorizeList = this.getAuthorizeList();
			if (tmp_authorizeList != null && tmp_authorizeList.size()>0){
				for (Iterator it = tmp_authorizeList.iterator();it.hasNext();){
					AuthorizeList authorize = (AuthorizeList)it.next();
					result.put(authorize.getAuthorizeTag(),authorize);
				}
			}
		}else{
			for (int i=0;i<groupArray.length;i++){
				AuGroup tmp_group = (AuGroup)this.groupDAO.selectGroup(new Integer(groupArray[i]));
				if (tmp_group != null){
					List tmp_authorizeList = this.getAuthorizeListByTag(tmp_group.getGroupAuthorize());
					if (tmp_authorizeList != null && tmp_authorizeList.size()>0){
						for (Iterator it = tmp_authorizeList.iterator();it.hasNext();){
							AuthorizeList authorize = (AuthorizeList)it.next();
							result.put(authorize.getAuthorizeTag(),authorize);
						}
					}
				}
			}
		}
		if (result.size()==0)
			return null;
		return result;
		
	}
	
	public String addGroup(AuGroup group){
		return this.groupDAO.insertAuGroup(group);
	}
	
	public String modifyGroup(AuGroup group){
		return this.groupDAO.updateAuGroup(group);
	}
	
	public String checkGroupValidate(AuGroup group){
		String result = ResultCode.OP_FAILED;
		if (group == null)
			return result;
		
		if (group.getGroupAuthorize().equals("") || group.getGroupAuthorize() == null){
			return ResultCode.OP_AUTHORIZE_MISS_SELECT;
		}
		
		try {
			AuGroup tmpGroup = this.groupDAO.selectGroup(group.getGroupName(),group.getModuleList()); 
			
			
			if (tmpGroup != null){
				if (group.getId() != null){
					if (group.getId().intValue() != tmpGroup.getId().intValue()){
						return ResultCode.OP_THE_NAME_EXISTS;
					}
				}else{
					return ResultCode.OP_THE_NAME_EXISTS;
				}
				
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			return result;
		}
		
		result = ResultCode.OP_SUCCESS;
		
		
		return result;
	}
	
	public AuGroup getGroup(Integer gid) throws SystemException{
		return this.groupDAO.selectGroup(gid);
	}
	
	public List getGroupListByModule(Integer mid) throws SystemException{
		ModuleList module = new ModuleList();
		module.setMid(mid);
		return this.groupDAO.selectGroups(module);
	}
	
	public List getGroupListByUser(String uid) throws SystemException{
		OperatorDetail op = this.getOperatorDetail(uid);
		if (op == null)
			return null;
		
		
		String idList = this.generatePhaseOfInCondition(op.getAuthorize(),"/");
		if (idList.indexOf(",") == -1 && idList.equals("000")){
			return this.getGroupList();
		}else{
			return this.groupDAO.selectGroups(idList);
		}
	}
	public List getGroupList() throws SystemException{
		
		return this.groupDAO.selectGroups();
	}
	
	public String deleteGroup(AuGroup group) throws SystemException{
		String result = ResultCode.OP_FAILED;
		List op_list = this.operatorDAO.selectOperatorsByAuthorize(group.getId().toString());
		
		if (op_list != null){
			for (Iterator it = op_list.iterator();it.hasNext();){
				OperatorDetail od = (OperatorDetail)it.next();
				
				StringBuffer sauthorize = new StringBuffer(od.getModuleAuthorize());
				int index = sauthorize.indexOf(group.getId().toString() + "/");
				sauthorize.delete(index,index + group.getId().toString().length() + 1);
				od.setAuthorize(sauthorize.toString());
				
				result = this.operatorDAO.updateOperator(od);
			}
			result = this.groupDAO.deleteAuGroup(group);
		}
		
		return result;
	}
	
	public String deleteOperatorApp(OperatorDetail od){
		if (od.getIsDelete().equals("0")){
			od.setIsDelete("1");
			return this.operatorDAO.updateOperator(od);
		}
		return ResultCode.OP_SUCCESS;
	}
	
	public String deleteOperatorVerification(OperatorDetail od){
		if (od.getIsDelete().equals("1")){
			od.setIsDelete("2");
			return this.operatorDAO.updateOperator(od);
		}
		return ResultCode.OP_SUCCESS;
	}
	
	

	public AuthorizeList getAuthorizeByAction(String action) throws SystemException {
		return this.authorizeDAO.selectAuthorizeByAction(action);
	}
	
	public AuthorizeList getAuthorize(Integer aid) throws SystemException{
		return this.authorizeDAO.selectAuthorize(aid);
	}

	public ModuleList getModule(Integer mId) throws SystemException {
		return this.moduleDAO.selectModule(mId);
	}
	
	public String addModule(ModuleList module){
		return this.moduleDAO.insertModule(module);
	}
	
	public String addAuthorize(AuthorizeList authorize){
		return this.authorizeDAO.insertAuthorize(authorize);
	}
	
	protected ModuleList getModuleByName(String moduleName) throws SystemException {
		return this.moduleDAO.selectModuleByName(moduleName);
	}
	
	protected ModuleList getModule(String moduleTag) throws SystemException {
		return this.moduleDAO.selectModule(moduleTag);
	}
	
	public String checkModuleValidate(ModuleList module){
		String result = ResultCode.OP_FAILED;
		
		if (module == null)
			return result;
		
		try {
			if ("".equals(module.getModuleName()) || this.getModuleByName(module.getModuleName()) != null)
				return ResultCode.OP_THE_NAME_EXISTS;
		
		
			if ("".equals(module.getModuleTag()) || this.getModule(module.getModuleTag()) != null){
				return ResultCode.OP_THE_TAG_EXISTS;
			}
			
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage());
			return ResultCode.OP_SYSTEM_DB_ERR;
			
		}
		
		result = ResultCode.OP_SUCCESS;
		
		return result;
	}
	
	public Page getModuleLists(int pageSize, int rowsPerPage) throws Exception{
		return this.moduleDAO.selectModules(pageSize, rowsPerPage);
	}

	//operator method
	public OperatorDetail getOperatorDetail(String loginId){
		return this.operatorDAO.selectOperator(new Integer(loginId));
	}
	
	/**
	 * 分页获取当前操作员子类列表
	 * @param od
	 * @param pageSize
	 * @param rowsPerPage
	 * @return
	 * @throws Exception
	 */
	public Page getOperatorListByParent(OperatorDetail od, int pageSize, int rowsPerPage) throws Exception{
		return this.operatorDAO.selectOperatorListByParent(od, pageSize, rowsPerPage);
	}
	
	protected String generatePhaseOfInCondition(String strSplitWithSlash, String splitPhase){
		String[] values = strSplitWithSlash.split(splitPhase);
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < values.length; i++){
			result.append(values[i]).append(",");
		}
		result.delete(result.length()-1,result.length());
		return result.toString();
	}
	
}
